package com.example.controller;

import com.example.info.LoginInfo;
import com.example.service.UserService;
import com.example.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RequestMapping("/login")
@RestController
public class LoginController {

    /**
     * 登录  --post   http://localhost:8881/login
     */
    @Autowired
    private UserService userService;
    @PostMapping
    @ResponseBody
    public String login(@RequestBody Map map){//axios的post方法把参数放到请求体中了，不能用requestparam
        String userName= (String) map.get("userName");
        String userPassword= (String) map.get("userPassword");
        LoginInfo loginInfo=userService.getPasswordByUserName(userName);
        if(loginInfo==null){
            return null;
        }
        if(userPassword.equals(loginInfo.getUserPassword())){
            Map<String,Object> claim=new HashMap<>();
            claim.put("userName",loginInfo.getUserName());
            claim.put("userId",loginInfo.getUserID());
            String token= JwtUtils.genToken(claim);
            System.out.println(token);
            Claims claims= JwtUtils.parseToken(token);
            log.info(String.valueOf(claims));
            log.info("生成token成功");
            return token;
        }
        return null;
    }
}
